from zope.interface import implements

import os, sys

APPLICATION_INSTALL_DIR = os.environ.get('SIMPLEWATCHER_INSTALL')
if not APPLICATION_INSTALL_DIR:
    raise EnvironmentError("must set environment variable SIMPLEWATCHER_INSTALL")
sys.path.append('%s/lib' % APPLICATION_INSTALL_DIR)

from watcher.interfaces import IWatcherContainer, IWatcherObject
from watcher.config import ConfigLoader, DEFAULT_CONFIG_PATH

class WatcherObject(object):
    """simple obj that handles it's own config loading"""
    implements(IWatcherObject)
    def __init__(self, configName, configPath=None, parent=None):
        if configPath is None:
            configPath = DEFAULT_CONFIG_PATH
        self.configPath = configPath
        self.config = ConfigLoader(configPath).load(configName)
        self.parent = parent
        self.__name__ = self.config.localName + "_" + self.config.name
        if IWatcherContainer.providedBy(self.parent):
            self.parent.setChild(self.__name__, self)
        

        

class WatcherContainer(WatcherObject):
    """implements standard container behavior"""
    implements(IWatcherContainer)
    def __init__(self, configName, configPath=None, parent=None):
        super(WatcherContainer, self).__init__(configName, configPath, parent)
        self.children = {} 

    """something to keep in mind:
       set child and remove child are not nice about what they do.  they will blow away
       whatever you already have in the children list by that name if you just drop
       a new child in of the same name.  assumes that you know what you intend
       if you setChild(name, dict)
    """

    def setChild(self, childKlassName, klass):
        """children are of the form container[name][info]"""
        self.children[childKlassName] = klass

    def removeChild(self, childKlassName):
        del(self.children[childKlassName])
 

